package com.furioussnails.sourcecodeanalysis.sqlsession;

import com.furioussnails.sourcecodeanalysis.config.BoundSql;
import com.furioussnails.sourcecodeanalysis.parsing.GenericTokenParser;
import com.furioussnails.sourcecodeanalysis.parsing.ParameterMapping;
import com.furioussnails.sourcecodeanalysis.parsing.ParameterMappingTokenHandler;
import com.furioussnails.sourcecodeanalysis.pojo.Configuration;
import com.furioussnails.sourcecodeanalysis.pojo.MapperStatement;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    public <T> List<T> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {

        //注册连接,获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //获取sql语句 这里的sql是带#{}或者${}站位符的  暂时不解析${}
        String sqlText = mapperStatement.getSqlText();

        BoundSql boundSql = getBoundSql(sqlText);
        
        //获取预处理对象
        PreparedStatement statement = connection.prepareStatement(boundSql.getSqlText());
        
        // 设置参数
        String paramType = mapperStatement.getParamType();
        Class<?> paramTypeClass = getClassType(paramType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            statement.setObject(i+1,o);
        }
        
        //执行sql
        ResultSet resultSet = statement.executeQuery();
        
        // 封装返回结果集
        String resultType = mapperStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        List<Object> list = new ArrayList<>();
        while (resultSet.next()){
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);
                
                // 使用反射或者内省 ,根据数据库表和实体的对应关系,完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            list.add(o);
        }

        return (List<T>) list;
    }

    private Class<?> getClassType(String paramType) throws ClassNotFoundException {
        if (paramType != null){
            Class<?> aClass = Class.forName(paramType);
            return aClass;
        }
        return null;
    }

    /**
     * 对#{} 站位符进行解析 
     * @param sqlText
     * @return
     */
    private BoundSql getBoundSql(String sqlText) {

        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        // 解析后的sql
        String parseSql = genericTokenParser.parse(sqlText);

        // 解析的参数
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }
}
